import React, { ReactElement, useState, useEffect, useCallback } from "react";
import "./index.css";
import axios from "axios";
import { message } from "antd";
import BtnSearch from "./BtnSearch";
import TableInfo from "./TableInfo";

const UserInfo: React.FC = (): ReactElement => {
  const [list, setList] = useState<any>([]);

  useEffect(() => {
    GetinfoData();
  }, []);

  const GetinfoData = async () => {
    const { data: res } = await axios.get(
      "http://139.196.93.237:3000/api/SelectOpinions"
    );
    res.data.sort((a: any, b: any) => {
      return a.time > b.time ? -1 : 1;
    });
    setList(res.data);
  };

  const onSearch = useCallback((val: []) => {
    setList(val);
  }, []);

  const removeInfo = useCallback((val: []) => {
    setList(val);
  }, []);

  const addInfo = useCallback((val: {}) => {
    addUserinfo(val);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const editInfo = useCallback((val: []) => {
    setList(val);
  }, []);

  //新增调用API
  const addUserinfo = async (val: {}) => {
    const { data: res } = await axios.post(
      "http://139.196.93.237:3000/api/SendOpinions",
      val
    );
    console.log(res);
    if (res.status === 200) {
      message.success("信息添加成功！");
      GetinfoData(); //更新数据
    }
  };

  return (
    <div className="user_info">
      <BtnSearch dataList={list} addInfo={addInfo} onSearch={onSearch} />
      <TableInfo dataList={list} removeInfo={removeInfo} editInfo={editInfo} />
    </div>
  );
};

export default UserInfo;
